package com.hyc.algorithm.Array;

import java.util.Arrays;

/**
 * @projectName: DataStructure
 * @package: com.hyc.algorithm.Array
 * @className: MergeArrDemo
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/2/28 0:34
 * @version: 1.0
 */
public class MergeArrDemo {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4, 5};
        int[] arr2 = {6, 7, 10, 13, 15};
        int[] ints = mergeArr(arr1, arr2);
        System.out.println(Arrays.toString(ints));
    }

    public static int[] mergeArr(int[] arr1, int[] arr2) {
        if (arr1 == null) {
            return arr2;
        }
        if (arr2 == null) {
            return arr1;
        }
        //结果集数组
        int[] result = new int[arr1.length + arr2.length];
        //记录第一个数组的遍历索引
        int p1 = 0;
        //记录第二个数组的遍历索引
        int p2 = 0;
        //记录结果数组的遍历索引
        int pr = 0;

        //只要有一个数组没有遍历完就继续循环
        while (p1 < arr1.length || p2 < arr2.length) {
            if (p2 >= arr2.length || p1 < arr1.length && arr1[p1] <= arr2[p2]) {
                result[pr] = arr1[p1];
                p1++;
            } else {
                result[pr] = arr2[p2];
                p2++;
            }
            pr++;
        }
        return result;
    }

}
